<script setup lang="ts">
import { ref } from 'vue';
import type { UploadFile, UploadProps } from 'ant-design-vue';
import { message } from 'ant-design-vue';
import { UploadOutlined } from '@ant-design/icons-vue';
import { createActivityApi } from '@/api/MicroScene/MicroSceneApi';

const props = defineProps<{
  open: boolean;
  areaId: string;
}>();

const emit = defineEmits<{
  (e: 'changeOpenState', openState: boolean): void;
  (e: 'success'): void;
}>();

const formState = ref({
  activityTitle: '',
  introduction: '',
  authors: [] as string[],
  targetUrl: '',
  tags: [] as string[],
  imageUrl: '',
});

const fileList = ref<UploadFile[]>([]);

const rules = {
  activityTitle: [{ required: true, message: '请输入活动标题' }],
  introduction: [{ required: true, message: '请输入活动简介' }],
  authors: [{ required: true, message: '请输入作者，多个作者用分号分隔' }],
  targetUrl: [{ required: true, message: '请输入活动链接' }],
  tags: [{ required: true, message: '请至少输入一个标签' }],
  imageUrl: [{ required: true, message: '请上传封面图' }],
};

const handleOk = async () => {
  try {
    if (!formState.value.imageUrl || !fileList.value[0]) {
      message.error('请上传封面图片');
      return;
    }

    await createActivityApi(
      formState.value.activityTitle,
      formState.value.introduction,
      formState.value.authors.join(';'),
      props.areaId,
      formState.value.targetUrl,
      formState.value.tags.join(','),
      fileList.value[0].originFileObj as File,
    );

    message.success('创建成功');
    emit('changeOpenState', false);
    emit('success');

    // 清空表单
    formState.value = {
      activityTitle: '',
      introduction: '',
      authors: [],
      targetUrl: '',
      tags: [],
      imageUrl: '',
    };
  }
  catch (error: any) {
    message.error(`创建失败：${error.message}`);
  }
};

const handleCancel = () => {
  emit('changeOpenState', false);
};

const beforeUpload: UploadProps['beforeUpload'] = (file) => {
  // 检查文件类型
  const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
  if (!isJpgOrPng) {
    message.error('只能上传 JPG/PNG 格式的图片！');
    return false;
  }

  // 检查文件大小
  const isLt2M = file?.size ? file.size / 1024 / 1024 < 2 : false;
  if (!isLt2M) {
    message.error('图片大小不能超过 2MB！');
    return false;
  }

  // 更新文件列表
  fileList.value = [file];

  // 创建本地预览
  const reader = new FileReader();
  reader.addEventListener('load', () => {
    formState.value.imageUrl = reader.result as string;
  });
  reader.readAsDataURL(file);

  return false;
};
</script>

<template>
  <a-modal :open="open" title="发布活动" :mask-closable="false" @ok="handleOk" @cancel="handleCancel">
    <a-form :model="formState" layout="vertical">
      <div style="display: flex; align-items: flex-start; gap: 1rem;">
        <a-form-item
          name="imageUrl"
        >
          <a-upload
            v-model:file-list="fileList"
            list-type="picture-card"
            :show-upload-list="false"
            :before-upload="beforeUpload"
            :multiple="false"
            :max-count="1"
          >
            <img
              v-if="formState.imageUrl"
              :src="formState.imageUrl"
              alt="avatar"
              style="width: 95%; height: 95%; object-fit: cover;"
            >
            <div v-else>
              <UploadOutlined />
              <div style="margin-top: 0.5rem;">
                上传封面图
              </div>
            </div>
          </a-upload>
        </a-form-item>

        <div style="flex: 1;">
          <a-form-item
            name="activityTitle"
            :rules="rules.activityTitle"
          >
            <a-input v-model:value="formState.activityTitle" placeholder="请输入活动标题" />
          </a-form-item>

          <a-form-item
            name="tags"
            :rules="rules.tags"
          >
            <a-select
              v-model:value="formState.tags"
              mode="tags"
              :open="false"
              placeholder="标签，输入后按回车键添加"
              style="width: 100%;"
              :token-separators="[',']"
            />
          </a-form-item>
        </div>
      </div>

      <a-form-item
        name="introduction"
        :rules="rules.introduction"
      >
        <a-textarea
          v-model:value="formState.introduction"
          placeholder="请输入活动简介"
          :auto-size="{ minRows: 3, maxRows: 5 }"
        />
      </a-form-item>

      <a-form-item
        name="authors"
        :rules="rules.authors"
      >
        <a-select
          v-model:value="formState.authors"
          mode="tags"
          :open="false"
          placeholder="作者，输入后按回车键添加"
          style="width: 100%;"
          :token-separators="[';']"
        />
      </a-form-item>

      <a-form-item
        name="targetUrl"
        :rules="rules.targetUrl"
      >
        <a-input v-model:value="formState.targetUrl" placeholder="请输入活动链接" />
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<style scoped>
.ant-form-item {
  margin-bottom: 0.5rem;
}
</style>
